# @Version        : 1.0
# @Update Time    : 2024/12/23 23:34
# @File           : cache_service.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
import json
from sqlalchemy import and_, select
from src.config import settings
from src.db.db_database import alchemy
from src.log import logger
from src.db.db_redis import AsyncRedisTool
from src.models import SysDictType, SysRole, SysMenu
from src.schemas import DictTypeSchemaCache
from src.services.dict_service import DictTypeService
from src.services.role_service import RoleService


class CacheService:
    @staticmethod
    async def get_dict_data_to_cache(param: dict | None = None):
        async with AsyncRedisTool.from_url() as redis:
            await redis.delete(f"{settings.cache.DICT_DATA_KEY}*")
            if param:
                for t in param.get("dict_type", []):
                    lst = []
                    for item in param.get("dict_data", []):
                        if item.get("dict_type_id") == t.get("id"):
                            lst.append(item)
                    await redis.set(
                        f"{settings.cache.DICT_DATA_KEY}{t.get('dict_type')}",
                        json.dumps(lst, ensure_ascii=False, default=str),
                    )
            else:
                async with alchemy.with_async_session() as session:
                    res = await DictTypeService(session=session).list(
                        load=[SysDictType.dict_datas],
                        uniquify=True,
                    )
                    res = [
                        DictTypeSchemaCache.model_validate(item).model_dump()
                        for item in res
                    ]
                    for item in res:
                        await redis.set(
                            f"{settings.cache.DICT_DATA_KEY}{item['dict_type']}",
                            json.dumps(
                                item.get("dict_datas", []),
                                ensure_ascii=False,
                                default=str,
                            ),
                        )

    # 缓存角色权限
    @staticmethod
    async def get_role_permission_to_cache(param: dict | None = None):
        async with AsyncRedisTool.from_url() as redis:
            if param:
                for item in param.get("role", []):
                    await redis.set(
                        f"{settings.cache.ROLE_KEY}{item.get('role_key')}",
                        json.dumps(
                            item.get("permissions", []), ensure_ascii=False, default=str
                        ),
                    )
            else:
                async with alchemy.with_async_session() as session:
                    res = await RoleService(session=session).list(
                        and_(
                            SysRole.status == "1",
                            SysMenu.status == "1",
                            SysMenu.menu_type == "3",
                        ),
                        statement=select(SysRole).join(SysRole.menus),
                        load=[SysRole.menus],
                        uniquify=True,
                    )
                    for item in res:
                        if item.role_key == "admin":
                            continue
                        perm_code = set(
                            item.permissions
                            for item in item.menus
                            if item.permissions is not None
                        )
                        logger.warning(item.role_key)
                        if perm_code:
                            await redis.set(
                                f"{settings.cache.ROLE_KEY}{item.role_key}",
                                json.dumps(
                                    list(perm_code), ensure_ascii=False, default=str
                                ),
                            )
